package com.lsh.oms.core.service.asynservice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.oms.api.model.status.MisArrivalDto;
import com.lsh.oms.api.model.status.UpdateStatusDto;
import com.lsh.oms.core.email.SendEmailService;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.model.email.EmailModel;
import com.lsh.oms.core.model.http.HttpMessage;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.model.order.OrderSignHead;
import com.lsh.oms.core.model.payment.OrderModel;
import com.lsh.oms.core.model.sms.SmsModel;
import com.lsh.oms.core.proxy.service.MisProxy;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.payment.OrderSignForRefundService;
import com.lsh.oms.core.utils.HttpUtils;
import com.lsh.oms.core.utils.SMSUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Project Name: lsh-oms
 * Created by peter
 * Date: 17/4/5
 * 北京链商电子商务有限公司
 * Package com.lsh.oms.core.service.AsyncService
 * desc:异步处理监听类
 *
 * @author peter
 */
@Component
public class AsyncEventListener implements IEventListener {
    private Logger logger = LoggerFactory.getLogger(AsyncEventListener.class);

    @Autowired
    private SendEmailService sendEmailService;

//    @Autowired
//    private FindOrderByMisService findOrderByMisService;

    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private OrderSignForRefundService orderSignForRefund;

    @Autowired
    private MisProxy misProxy;

    @Value("${elasticsearch.oms.ip}")
    private String esIp;


    /**
     * 发送邮件
     *
     * @param emailModel 监听类
     */
    @Subscribe
    @AllowConcurrentEvents
    public void sendEmail(EmailModel emailModel) {
        logger.info("sendEmail()");
        sendEmailService.send(emailModel.getContent(), emailModel.getTitle(), emailModel.getToEmails());
    }

    /**
     * @param orderModel
     */
    @Subscribe
    @AllowConcurrentEvents
    public void sendPayNotify(OrderModel orderModel) {
        logger.info("orderModel is {}", JSON.toJSONString(orderModel));
        OrderHead head = orderQueryService.findByCode(orderModel.getOrderCode(), false, false);
        misProxy.payFreight(orderModel.getOrderCode(), head.getVenderId());
    }


    /**
     * 发送短信
     *
     * @param smsModel 监听类
     */
    @Subscribe
    @AllowConcurrentEvents
    public void sendSMS(SmsModel smsModel) {
        logger.info(smsModel.getLogSign() + " ,smsEmail()" + JSON.toJSONString(smsModel.getSmsParams()));
        SMSUtils.signSMS(smsModel.getSmsParams(), smsModel.getSmsUrl(), smsModel.getLogSign());
    }

    /**
     * 判断订单是否是部分签收,如果是,插入task,请求商城退款!!
     * 目前,该方法,在OtherSysSynRestService类的updateArrivalStatus方法中触发,
     *
     * @param misArrivalDto
     */
    @Subscribe
    @AllowConcurrentEvents
    public void orderSignForRefundCheck(MisArrivalDto misArrivalDto) {
        String logSign = UUID.randomUUID().toString();
        logger.info("【签收--check】logSign: {},  param －－> {}", logSign, JsonUtils.obj2Json(misArrivalDto));

        List<Long> receiptOrderIds = JSON.parseArray(misArrivalDto.getReceiptOrderId(), Long.class);
        List<JSONObject> receiptOrderList = new ArrayList<>();//TODO 2019-09-11
//                findOrderByMisService.getReceiptOrderList(receiptOrderIds, InterfaceEnum.RECEIPT_LIST, logSign,);

        for (JSONObject jsonObject : receiptOrderList) {
            Long orderCode = jsonObject.getLong("order_id");
            if (orderCode != null && orderCode != 0L) {
                try {
                    orderSignForRefund.orderSignForRefund(orderCode);
                } catch (BusinessException e) {
                    logger.error("【签收--check】 orderCode: " + orderCode + ",异常信息: " + e.getMessage());
                } catch (Exception e) {
                    logger.error("【签收--check】 orderCode: " + orderCode + ",异常信息: " + e.getMessage(), e);
                }
            }
        }
    }

    @Subscribe
    @AllowConcurrentEvents
    public void orderSignForRefundCheck(UpdateStatusDto dto) {
        String logSign = UUID.randomUUID().toString();
        logger.info("【order 签收--check】logSign: {},  param －－> {}", logSign, JsonUtils.obj2Json(dto));

        Long orderCode = dto.getOrderNo();
        if (orderCode != null && orderCode != 0L) {
            try {
                orderSignForRefund.orderFinishForCoupon(orderCode);
                orderSignForRefund.orderSignForRefund(orderCode);
            } catch (BusinessException e) {
                logger.error("【order 签收--check】 orderCode: " + orderCode + ",异常信息: " + e.getMessage());
            } catch (Exception e) {
                logger.error("【order 签收--check】 orderCode: " + orderCode + ",异常信息: " + e.getMessage(), e);
            }
        }
    }


    @Subscribe
    @AllowConcurrentEvents
    public void orderSignForRefundCheck(OrderSignHead orderSignHead) {
        String logSign = UUID.randomUUID().toString();
        logger.info("【order 签收--check】logSign: {},  param －－> {}", logSign, JsonUtils.obj2Json(orderSignHead));

        Long orderCode = orderSignHead.getOrderId();
        if (orderCode != null && orderCode != 0L) {
            try {
                orderSignForRefund.orderFinishForCoupon(orderCode);
                orderSignForRefund.orderSignForRefund(orderCode);
            } catch (BusinessException e) {
                logger.error("【order 签收--check】 orderCode: " + orderCode + ",异常信息: " + e.getMessage());
            } catch (Exception e) {
                logger.error("【order 签收--check】 orderCode: " + orderCode + ",异常信息: " + e.getMessage(), e);
            }
        }
    }

    @Subscribe
    @AllowConcurrentEvents
    public void deleteOrderInfoFromEs(OrderHead orderHead) {
        if (orderHead == null) {
            return;
        }
        Long orderCode = orderHead.getOrderCode();
        if (orderCode == null || orderCode.intValue() == 0L) {
            return;
        }

        String url = esIp + "/oms/order/" + orderCode.toString();
        try {
            logger.info("From Es, delete order info start! orderCode: " + orderCode);
            HttpMessage httpMessage = HttpUtils.sendDeleteRequest(url);
            logger.info("From Es, delete order info end! orderCode: {}, response: {}", orderCode, JSON.toJSONString(httpMessage));
        } catch (IOException e) {
            logger.error("From Es, delete order info failed! orderCode: " + orderCode, e);
        }
    }

}
